package tech.edwardvan.springbootdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import tech.edwardvan.springbootdemo.common.ServerResponse;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全局异常处理器
 *
 * @author EdwardVan
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionConfig {

    @ExceptionHandler(Exception.class)
    public ServerResponse globalError(Exception e) {
        e.printStackTrace();
        return ServerResponse.errorMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ServerResponse methodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        //优化异常展示
        Map<String, String> errorMap = new HashMap();
        e.getBindingResult().getFieldErrors().forEach(fieldError -> errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
        return ServerResponse.error(errorMap);
    }
}
